

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';
import Header from '../../components/Header';

// 后端返回的内容数据结构
interface ContentVO {
  id: number;
  title: string;
  description: string;
  content: string;
  contentType: string;
  category: string;
  tags: string[];
  imageUrl: string;
  videoUrl: string;
  duration: number;
  difficulty: number;
  status: number;
  viewCount: number;
  likeCount: number;
  collectCount: number;
  createTime: string;
  updateTime: string;
  user: {
    id: number;
    userName: string;
    userAvatar: string;
  };
  hasLiked: boolean;
  hasCollected: boolean;
}

// 分页响应结构
interface PageResponse<T> {
  records: T[];
  total: number;
  size: number;
  current: number;
  pages: number;
}

// API响应结构
interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}

// 前端展示用的内容项结构
interface ContentItem {
  id: string;
  title: string;
  description: string;
  category: string;
  difficulty: string;
  views: string;
  likes: string;
  publishTime: string;
  imageUrl: string;
}

const CognitionHomePage: React.FC = () => {
  const navigate = useNavigate();
  
  // 状态管理
  const [localSearchValue, setLocalSearchValue] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('分类');
  const [selectedDifficulty, setSelectedDifficulty] = useState('难度');
  const [selectedSort, setSelectedSort] = useState('推荐');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(6);
  const [totalCount, setTotalCount] = useState(0);
  const [contentItems, setContentItems] = useState<ContentItem[]>([]);
  const [loading, setLoading] = useState(false);
  
  // 下拉菜单显示状态
  const [showCategoryDropdown, setShowCategoryDropdown] = useState(false);
  const [showDifficultyDropdown, setShowDifficultyDropdown] = useState(false);
  const [showSortDropdown, setShowSortDropdown] = useState(false);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '认知提升 - 精进坊';
    return () => { document.title = originalTitle; };
  }, []);

  // 获取内容数据
  const fetchContentData = async () => {
    setLoading(true);
    try {
      // 构建查询参数
      const queryParams: any = {
        current: currentPage,
        pageSize: pageSize,
        category: 'cognition', // 固定为认知类型
        status: 1 // 只获取已发布的内容
      };

      // 添加搜索条件
      if (localSearchValue.trim()) {
        queryParams.searchText = localSearchValue.trim();
      }

      // 添加分类筛选（这里是子分类）
      if (selectedCategory !== '分类') {
        queryParams.tags = [selectedCategory];
      }

      // 添加难度筛选
      if (selectedDifficulty !== '难度') {
        const difficultyMap: Record<string, number> = {
          '入门': 1,
          '初级': 2,
          '进阶': 3,
          '高级': 4,
          '专家': 5
        };
        queryParams.difficulty = difficultyMap[selectedDifficulty];
      }

      // 添加排序
      if (selectedSort !== '推荐') {
        const sortMap: Record<string, { field: string; order: string }> = {
          '最新发布': { field: 'createTime', order: 'descend' },
          '最热': { field: 'viewCount', order: 'descend' }
        };
        const sortConfig = sortMap[selectedSort];
        if (sortConfig) {
          queryParams.sortField = sortConfig.field;
          queryParams.sortOrder = sortConfig.order;
        }
      }

      console.log('发送API请求:', queryParams);

      const response = await fetch('/api/content/list/page/vo', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(queryParams),
      });

      console.log('API响应状态:', response.status);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result: ApiResponse<PageResponse<ContentVO>> = await response.json();
      
      console.log('API响应数据:', result);
      
      if (result.code === 0) {
        // 转换数据格式
         const items: ContentItem[] = result.data.records.map(item => ({
           id: (item.id || 0).toString(),
           title: item.title || '未知标题',
           description: item.description || '暂无描述',
           category: (item.tags && item.tags.length > 0) ? item.tags[0] : '认知提升',
           difficulty: getDifficultyText(item.difficulty || 1),
           views: formatNumber(item.viewCount || 0) + '次',
           likes: formatNumber(item.likeCount || 0),
           publishTime: formatTime(item.createTime || new Date().toISOString()),
           imageUrl: item.imageUrl || 'https://s.coze.cn/image/quHpKpndnNo/'
         }));

        setContentItems(items);
        setTotalCount(result.data.total);
        console.log('成功获取内容:', items.length, '条');
      } else {
        console.error('获取内容失败:', result.message);
        // 如果API调用失败，使用默认数据
        setContentItems(getDefaultContentItems());
        setTotalCount(6);
      }
    } catch (error) {
      console.error('获取内容数据失败:', error);
      // 如果API调用失败，使用默认数据
      setContentItems(getDefaultContentItems());
      setTotalCount(6);
    } finally {
      setLoading(false);
    }
  };

  // 格式化数字显示
  const formatNumber = (num: number): string => {
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + '万';
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + '千';
    }
    return num.toString();
  };

  // 获取难度文本
  const getDifficultyText = (difficulty: number): string => {
    const difficultyMap: Record<number, string> = {
      1: '入门',
      2: '初级',
      3: '进阶',
      4: '高级',
      5: '专家'
    };
    return difficultyMap[difficulty] || '入门';
  };

  // 格式化时间显示
  const formatTime = (timeStr: string): string => {
    const time = new Date(timeStr);
    const now = new Date();
    const diff = now.getTime() - time.getTime();
    
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor(diff / (1000 * 60));
    
    if (days > 0) {
      return `${days}天前`;
    } else if (hours > 0) {
      return `${hours}小时前`;
    } else if (minutes > 0) {
      return `${minutes}分钟前`;
    } else {
      return '刚刚';
    }
  };

  // 获取默认内容数据（作为备用）
  const getDefaultContentItems = (): ContentItem[] => [
    {
      id: 'cognition-1',
      title: '批判性思维：如何建立理性思考框架',
      description: '掌握批判性思维的核心方法，学会独立思考和理性判断，提升决策质量。',
      category: '思维模型',
      difficulty: '进阶',
      views: '1.2万次',
      likes: '856',
      publishTime: '2天前',
      imageUrl: 'https://s.coze.cn/image/quHpKpndnNo/'
    },
    {
      id: 'cognition-2',
      title: '第一性原理：从根本上解决问题的思维方法',
      description: '深度解析埃隆·马斯克的思维模式，学会从本质出发思考和解决复杂问题。',
      category: '思维模型',
      difficulty: '专家',
      views: '8.9千次',
      likes: '623',
      publishTime: '1天前',
      imageUrl: 'https://s.coze.cn/image/v29iQBioYL0/'
    },
    {
      id: 'cognition-3',
      title: '认知偏差：常见的思维陷阱与避免方法',
      description: '了解常见的认知偏差，学会识别和避免思维陷阱，做出更理性的决策。',
      category: '心理学知识',
      difficulty: '入门',
      views: '15.6万次',
      likes: '2.1千',
      publishTime: '3天前',
      imageUrl: 'https://s.coze.cn/image/dsvdsGsa-cU/'
    },
    {
      id: 'cognition-4',
      title: '贝叶斯思维：在不确定世界中做决策',
      description: '学习贝叶斯推理的基本原理，在信息不完全的情况下做出最优决策。',
      category: '决策能力',
      difficulty: '进阶',
      views: '7.3千次',
      likes: '445',
      publishTime: '5天前',
      imageUrl: 'https://s.coze.cn/image/r0MrS6cFfZY/'
    },
    {
      id: 'cognition-5',
      title: '系统思维：复杂问题的分析与解决',
      description: '掌握系统思考的工具和方法，理解复杂系统的运作规律，找到根本解决方案。',
      category: '思维模型',
      difficulty: '专家',
      views: '9.2千次',
      likes: '567',
      publishTime: '1周前',
      imageUrl: 'https://s.coze.cn/image/I1RBbEBb5xE/'
    },
    {
      id: 'cognition-6',
      title: '情绪智力：理解和管理自己的情绪',
      description: '提升情商，学会识别、理解和管理自己的情绪，改善人际关系和决策质量。',
      category: '心理学知识',
      difficulty: '入门',
      views: '12.4万次',
      likes: '1.8千',
      publishTime: '1周前',
      imageUrl: 'https://s.coze.cn/image/J6Ur2tWwqeI/'
    }
  ];

  // 初始加载和依赖更新时获取数据
  useEffect(() => {
    fetchContentData();
  }, [currentPage, pageSize, selectedCategory, selectedDifficulty, selectedSort]);

  // 本地搜索防抖处理
  useEffect(() => {
    const timer = setTimeout(() => {
      if (localSearchValue !== '') {
        fetchContentData();
      }
    }, 500);

    return () => clearTimeout(timer);
  }, [localSearchValue]);

  // 处理本地搜索
  const handleLocalSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setLocalSearchValue(e.target.value);
  };

  // 处理分类筛选
  const handleCategorySelect = (category: string) => {
    setSelectedCategory(category === 'all' ? '分类' : category);
    setShowCategoryDropdown(false);
    console.log('筛选分类:', category);
  };

  // 处理难度筛选
  const handleDifficultySelect = (difficulty: string) => {
    setSelectedDifficulty(difficulty === 'all' ? '难度' : difficulty);
    setShowDifficultyDropdown(false);
    console.log('筛选难度:', difficulty);
  };

  // 处理排序
  const handleSortSelect = (sort: string) => {
    const sortTextMap: Record<string, string> = {
      'recommend': '推荐',
      'latest': '最新发布',
      'popular': '最热'
    };
    setSelectedSort(sortTextMap[sort]);
    setShowSortDropdown(false);
    console.log('排序方式:', sort);
  };

  // 处理内容卡片点击
  const handleContentCardClick = (contentId: string) => {
    navigate(`/content-detail?id=${contentId}`);
  };

  // 处理分页
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    console.log('跳转到第', page, '页');
  };

  // 处理上一页
  const handlePrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
      console.log('上一页');
    }
  };

  // 处理下一页
  const handleNextPage = () => {
    const totalPages = Math.ceil(totalCount / pageSize);
    if (currentPage < totalPages) {
      setCurrentPage(currentPage + 1);
      console.log('下一页');
    }
  };

  // 处理每页显示数量变更
  const handlePageSizeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newPageSize = parseInt(e.target.value);
    setPageSize(newPageSize);
    setCurrentPage(1); // 重置到第一页
    console.log('每页显示:', newPageSize, '条');
  };

  // 获取分类背景色
  const getCategoryBgColor = (category: string) => {
    switch (category) {
      case '思维模型':
        return 'bg-secondary';
      case '心理学知识':
        return 'bg-blue-500';
      case '决策能力':
        return 'bg-purple-500';
      default:
        return 'bg-secondary';
    }
  };

  // 关闭所有下拉菜单
  const closeAllDropdowns = () => {
    setShowCategoryDropdown(false);
    setShowDifficultyDropdown(false);
    setShowSortDropdown(false);
  };

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Element;
      const dropdowns = document.querySelectorAll('[data-dropdown]');
      const isClickInside = Array.from(dropdowns).some(dropdown => 
        dropdown.contains(target)
      );
      
      if (!isClickInside) {
        closeAllDropdowns();
      }
    };

    document.addEventListener('click', handleClickOutside);
    return () => {
      document.removeEventListener('click', handleClickOutside);
    };
  }, []);

  return (
    <div className={styles.pageWrapper}>
      <Header currentPage="cognition" />

      {/* 主布局容器 */}
      <div className="pt-16 min-h-screen">
        {/* 主内容区 */}
        <main className="p-6">
          {/* 页面头部 */}
          <div className="mb-8">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-2xl font-bold text-text-primary mb-2">认知提升</h2>
                <nav className="text-sm text-text-secondary">
                  <Link to="/home" className="hover:text-secondary">首页</Link>
                  <span className="mx-2">{'>'}</span>
                  <span>认知提升</span>
                </nav>
              </div>
            </div>
          </div>

          {/* 工具栏区域 */}
          <div className="bg-white rounded-card shadow-card p-4 mb-6">
            <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
              {/* 搜索框 */}
              <div className="relative flex-1 lg:max-w-md">
                <input 
                  type="text" 
                  placeholder="搜索认知提升内容..." 
                  value={localSearchValue}
                  onChange={handleLocalSearchChange}
                  className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
                />
                <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
              </div>
              
              {/* 筛选和排序 */}
              <div className="flex flex-wrap items-center gap-3">
                {/* 分类筛选 */}
                <div className="relative" data-dropdown>
                  <button 
                    onClick={() => {
                      setShowCategoryDropdown(!showCategoryDropdown);
                      setShowDifficultyDropdown(false);
                      setShowSortDropdown(false);
                    }}
                    className="flex items-center space-x-2 px-3 py-2 border border-gray-200 rounded-lg text-text-secondary hover:border-secondary hover:text-secondary"
                  >
                    <span>{selectedCategory}</span>
                    <i className="fas fa-chevron-down text-xs"></i>
                  </button>
                  {showCategoryDropdown && (
                    <div className="absolute top-full left-0 mt-2 w-48 bg-white border border-gray-200 rounded-lg shadow-lg z-10">
                      <div className="p-2">
                        <button 
                          onClick={() => handleCategorySelect('all')}
                          className="w-full text-left px-3 py-2 rounded-md hover:bg-gray-100"
                        >
                          全部
                        </button>
                        <button 
                          onClick={() => handleCategorySelect('思维模型')}
                          className="w-full text-left px-3 py-2 rounded-md hover:bg-gray-100"
                        >
                          思维模型
                        </button>
                        <button 
                          onClick={() => handleCategorySelect('心理学知识')}
                          className="w-full text-left px-3 py-2 rounded-md hover:bg-gray-100"
                        >
                          心理学知识
                        </button>
                        <button 
                          onClick={() => handleCategorySelect('决策能力')}
                          className="w-full text-left px-3 py-2 rounded-md hover:bg-gray-100"
                        >
                          决策能力
                        </button>
                      </div>
                    </div>
                  )}
                </div>
                
                {/* 难度筛选 */}
                <div className="relative" data-dropdown>
                  <button 
                    onClick={() => {
                      setShowDifficultyDropdown(!showDifficultyDropdown);
                      setShowCategoryDropdown(false);
                      setShowSortDropdown(false);
                    }}
                    className="flex items-center space-x-2 px-3 py-2 border border-gray-200 rounded-lg text-text-secondary hover:border-secondary hover:text-secondary"
                  >
                    <span>{selectedDifficulty}</span>
                    <i className="fas fa-chevron-down text-xs"></i>
                  </button>
                  {showDifficultyDropdown && (
                    <div className="absolute top-full left-0 mt-2 w-36 bg-white border border-gray-200 rounded-lg shadow-lg z-10">
                      <div className="p-2">
                        <button 
                          onClick={() => handleDifficultySelect('all')}
                          className="w-full text-left px-3 py-2 rounded-md hover:bg-gray-100"
                        >
                          全部
                        </button>
                        <button 
                          onClick={() => handleDifficultySelect('入门')}
                          className="w-full text-left px-3 py-2 rounded-md hover:bg-gray-100"
                        >
                          入门
                        </button>
                        <button 
                          onClick={() => handleDifficultySelect('进阶')}
                          className="w-full text-left px-3 py-2 rounded-md hover:bg-gray-100"
                        >
                          进阶
                        </button>
                        <button 
                          onClick={() => handleDifficultySelect('专家')}
                          className="w-full text-left px-3 py-2 rounded-md hover:bg-gray-100"
                        >
                          专家
                        </button>
                      </div>
                    </div>
                  )}
                </div>
                
                {/* 排序 */}
                <div className="relative" data-dropdown>
                  <button 
                    onClick={() => {
                      setShowSortDropdown(!showSortDropdown);
                      setShowCategoryDropdown(false);
                      setShowDifficultyDropdown(false);
                    }}
                    className="flex items-center space-x-2 px-3 py-2 border border-gray-200 rounded-lg text-text-secondary hover:border-secondary hover:text-secondary"
                  >
                    <span>{selectedSort}</span>
                    <i className="fas fa-chevron-down text-xs"></i>
                  </button>
                  {showSortDropdown && (
                    <div className="absolute top-full left-0 mt-2 w-40 bg-white border border-gray-200 rounded-lg shadow-lg z-10">
                      <div className="p-2">
                        <button 
                          onClick={() => handleSortSelect('recommend')}
                          className="w-full text-left px-3 py-2 rounded-md hover:bg-gray-100"
                        >
                          推荐
                        </button>
                        <button 
                          onClick={() => handleSortSelect('latest')}
                          className="w-full text-left px-3 py-2 rounded-md hover:bg-gray-100"
                        >
                          最新发布
                        </button>
                        <button 
                          onClick={() => handleSortSelect('popular')}
                          className="w-full text-left px-3 py-2 rounded-md hover:bg-gray-100"
                        >
                          最热
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* 内容展示区域 */}
          <div className="mb-8">
            {loading ? (
              <div className="flex items-center justify-center py-20">
                <div className="text-center">
                  <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-secondary mx-auto mb-4"></div>
                  <p className="text-text-secondary">正在加载内容...</p>
                </div>
              </div>
            ) : contentItems.length === 0 ? (
              <div className="flex items-center justify-center py-20">
                <div className="text-center">
                  <i className="fas fa-search text-4xl text-gray-300 mb-4"></i>
                  <p className="text-text-secondary">暂无相关内容</p>
                </div>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {contentItems.map((item) => (
                  <div 
                    key={item.id}
                    onClick={() => handleContentCardClick(item.id)}
                    className={`${styles.contentCard} rounded-card shadow-card ${styles.cardHover} cursor-pointer`}
                  >
                    <div className="relative">
                      <img 
                        src={item.imageUrl} 
                        alt={`${item.title}封面`} 
                        className="w-full h-48 object-cover rounded-t-card"
                      />
                      <div className={`absolute top-3 left-3 ${getCategoryBgColor(item.category)} text-white px-2 py-1 rounded-full text-xs font-medium`}>
                        {item.category}
                      </div>
                      <div className="absolute top-3 right-3 bg-gray-800 bg-opacity-70 text-white px-2 py-1 rounded-full text-xs">
                        {getDifficultyText(item.difficulty)}
                      </div>
                    </div>
                    <div className="p-5">
                      <h4 className="font-semibold text-text-primary mb-2 line-clamp-2">{item.title}</h4>
                      <p className="text-text-secondary text-sm mb-4 line-clamp-2">{item.description}</p>
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-4 text-xs text-text-secondary">
                          <span><i className="fas fa-play mr-1"></i>{formatNumber(item.viewCount || 0)}</span>
                          <span><i className="fas fa-heart mr-1"></i>{formatNumber(item.likeCount || 0)}</span>
                        </div>
                        <span className="text-xs text-text-secondary">{formatTime(item.createTime)}</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 分页区域 */}
          {!loading && contentItems.length > 0 && (
            <div className="flex items-center justify-between bg-white rounded-card shadow-card p-4">
              <div className="text-sm text-text-secondary">
                显示第 <span>{(currentPage - 1) * pageSize + 1}</span> - <span>{Math.min(currentPage * pageSize, totalCount)}</span> 条，共 <span>{totalCount}</span> 条结果
              </div>
              
              <div className="flex items-center space-x-2">
                <button 
                  onClick={handlePrevPage}
                  disabled={currentPage === 1}
                  className="px-3 py-2 border border-gray-200 rounded-lg text-text-secondary hover:border-secondary hover:text-secondary disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i className="fas fa-chevron-left"></i>
                </button>
                
                <div className="flex items-center space-x-1">
                  {(() => {
                    const totalPages = Math.ceil(totalCount / pageSize);
                    const pages = [];
                    
                    if (totalPages <= 7) {
                      // 如果总页数小于等于7，显示所有页码
                      for (let i = 1; i <= totalPages; i++) {
                        pages.push(
                          <button 
                            key={i}
                            onClick={() => handlePageChange(i)}
                            className={`px-3 py-2 rounded-lg ${currentPage === i ? styles.paginationActive : 'text-text-secondary hover:bg-secondary hover:text-white'}`}
                          >
                            {i}
                          </button>
                        );
                      }
                    } else {
                      // 复杂分页逻辑
                      if (currentPage <= 4) {
                        for (let i = 1; i <= 5; i++) {
                          pages.push(
                            <button 
                              key={i}
                              onClick={() => handlePageChange(i)}
                              className={`px-3 py-2 rounded-lg ${currentPage === i ? styles.paginationActive : 'text-text-secondary hover:bg-secondary hover:text-white'}`}
                            >
                              {i}
                            </button>
                          );
                        }
                        pages.push(<span key="ellipsis1" className="px-2 text-text-secondary">...</span>);
                        pages.push(
                          <button 
                            key={totalPages}
                            onClick={() => handlePageChange(totalPages)}
                            className={`px-3 py-2 rounded-lg ${currentPage === totalPages ? styles.paginationActive : 'text-text-secondary hover:bg-secondary hover:text-white'}`}
                          >
                            {totalPages}
                          </button>
                        );
                      } else if (currentPage >= totalPages - 3) {
                        pages.push(
                          <button 
                            key={1}
                            onClick={() => handlePageChange(1)}
                            className={`px-3 py-2 rounded-lg ${currentPage === 1 ? styles.paginationActive : 'text-text-secondary hover:bg-secondary hover:text-white'}`}
                          >
                            1
                          </button>
                        );
                        pages.push(<span key="ellipsis2" className="px-2 text-text-secondary">...</span>);
                        for (let i = totalPages - 4; i <= totalPages; i++) {
                          pages.push(
                            <button 
                              key={i}
                              onClick={() => handlePageChange(i)}
                              className={`px-3 py-2 rounded-lg ${currentPage === i ? styles.paginationActive : 'text-text-secondary hover:bg-secondary hover:text-white'}`}
                            >
                              {i}
                            </button>
                          );
                        }
                      } else {
                        pages.push(
                          <button 
                            key={1}
                            onClick={() => handlePageChange(1)}
                            className={`px-3 py-2 rounded-lg ${currentPage === 1 ? styles.paginationActive : 'text-text-secondary hover:bg-secondary hover:text-white'}`}
                          >
                            1
                          </button>
                        );
                        pages.push(<span key="ellipsis3" className="px-2 text-text-secondary">...</span>);
                        for (let i = currentPage - 1; i <= currentPage + 1; i++) {
                          pages.push(
                            <button 
                              key={i}
                              onClick={() => handlePageChange(i)}
                              className={`px-3 py-2 rounded-lg ${currentPage === i ? styles.paginationActive : 'text-text-secondary hover:bg-secondary hover:text-white'}`}
                            >
                              {i}
                            </button>
                          );
                        }
                        pages.push(<span key="ellipsis4" className="px-2 text-text-secondary">...</span>);
                        pages.push(
                          <button 
                            key={totalPages}
                            onClick={() => handlePageChange(totalPages)}
                            className={`px-3 py-2 rounded-lg ${currentPage === totalPages ? styles.paginationActive : 'text-text-secondary hover:bg-secondary hover:text-white'}`}
                          >
                            {totalPages}
                          </button>
                        );
                      }
                    }
                    
                    return pages;
                  })()}
                </div>
                
                <button 
                  onClick={handleNextPage}
                  disabled={currentPage >= Math.ceil(totalCount / pageSize)}
                  className="px-3 py-2 border border-gray-200 rounded-lg text-text-secondary hover:border-secondary hover:text-secondary disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i className="fas fa-chevron-right"></i>
                </button>
              </div>
              
              <div className="flex items-center space-x-2">
                <span className="text-sm text-text-secondary">每页</span>
                <select 
                  value={pageSize}
                  onChange={handlePageSizeChange}
                  className="border border-gray-200 rounded-lg px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-secondary"
                >
                  <option value={6}>6</option>
                  <option value={12}>12</option>
                  <option value={24}>24</option>
                </select>
                <span className="text-sm text-text-secondary">条</span>
              </div>
            </div>
          )}
        </main>
      </div>
    </div>
  );
};

export default CognitionHomePage;

